<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Project
 *
 * @author geminiblue
 */
class Project extends NetModel
{
    //put your code here
    public $projectName;
    public $projectId;
    public $invest_amount;
    const PROJECT_MYT     = 1;
    const PROJECT_CAR     = 2;
    const PROJECT_HOUSE   = 3;
    const PROJECT_REDWOOD = 4;
    const PROJECT_SEAFOOD = 5;
    const PROJECT_ZENGXIN = 6;
    const PROJECT_QIYE    = 7;
    public function attributeLabels() {
        return array(
            'projectId'=>'项目编号',
            'invest_amount'=>'投资金额',
        );
    }
    private function getTableName()
    {
        return '';
    }
    public function init()
    {
        parent::init();
    }
    public function getPrimaryKey(){
        return 'project_id';
    }

    public function rules() {
        return array(
          array('projectId','required'),
          array('invest_amount','required','CalculateInterest'),
        );
    }
    
    public function findByPK($id)
    {
        if(!is_numeric($id))
        {
            $this->setResult(array(
                'success' => 0,
                'msg'     => '项目id不正确',
            ));
        }
        $cache  = Yii::app()->cache_new->hget('projectDetail',$id);
        if($cache)
            return json_decode($cache);
        $remote = HttpLib::get('project/detail/get.json',array('project_id' => $id));
        if(!$remote->success)
        {
            $this->setResult(array(
                'success' => 0,
                'msg'     => $remote->errorMsg,
            ));
        }
        return $remote->result;
    }
    /**
     * 获取项目可投金额
     */
    public function getBalance($projectId)
    {
        return intval(Yii::app()->cache2->get($projectId . ".Investable"));
    }

    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    public static function getTypeDesc($typeCode)
    {
        $typeCode = intval($typeCode);
        $types = array(
            1  => "贸易通",
            2  => "汽赚宝",
            3  => "房赚宝",
            4  => "红木宝",
            5  => "海鲜宝",
            6  => '增信宝',
            7  => '优企贷',
            10 => '融易通',
        );
        if(in_array($typeCode, array_keys($types)))
            return $types[$typeCode];
        return "贸易通";
    }
    /**
     * 判断是否是新人专享项目
     * @return boolean [description]
     */
    public static function isOnlyForNew($project_id)
    {
        $project = self::model()->findByPK($project_id);
        return $project->property == 1 ;
    }
    /**
     * 获取精品推荐项目
     */
    public  function getRecommendProject($user_id,$token)
    {
        $controller = Yii::app()->controller;
        if($controller->checkUserToken($user_id,$token) && User::model()->invested($user_id))
        {
            $cache = Yii::app()->cache_new->hget('projectList','compertivie_login');
            $spentTime = number_format((microtime(true) - YII_BEGIN_TIME)*1000,2);
            Yii::log('to  redis hget projectList compertivie_login spent '.$spentTime.' ms','info','api.performance.info');
        }
        else
        {
            $cache     = Yii::app()->cache_new->hget('projectList','compertivie_not_login');
            $spentTime = number_format((microtime(true) - YII_BEGIN_TIME)*1000,2);
            Yii::log('to recommend redis hget projectList compertivie_not_login spent '.$spentTime.' ms','info','api.performance.info');
        }
        if($cache)
        {
            $project = json_decode($cache);
            $spentTime = number_format((microtime(true) - YII_BEGIN_TIME)*1000,2);
            Yii::log('to json_decode  spent '.$spentTime.' ms','info','api.performance.info');
        }
        else
        {
            $remote = HttpLib::post(Yii::app()->params['scripts']['project_recommend'],array('user_id'=>$user_id,'token'=>$token));
            $spentTime = number_format((microtime(true) - YII_BEGIN_TIME)*1000,2);
            Yii::log('to httpLib java  spent '.$spentTime.' ms','info','api.performance.info');
            if($remote->success && $remote->result)
                $project = $remote->result;
            else
            {
                $this->setResult(array(
                    'success' => 0,
                    'msg'     => $remote->errorMsg,
                ));
            }
        }
        $pipe  = Yii::app()->cache_ext->pipeline();
        $pipe->get($project->projectId . ".Investable");
        $pipe->get('PlatformInvestedAmountTotal');
        $pdata = $pipe->exec();
        $spentTime = number_format((microtime(true) - YII_BEGIN_TIME)*1000,2);
        Yii::log('to redis 163 pipiline  spent '.$spentTime.' ms','info','api.performance.info');
        $project->reduceDay          = $project->projectDuration;
        $project->projectBalance     = intval($pdata[0]);
        $project->projectIncomeFirst = sprintf("%.2f",$project->annualizedRate);
        $project->projectIncomeLast  = sprintf("%.2f",$project->annualizedRate);
        $project->process            = $controller->converPoint($project->projectBalance, $project->totalAmount);
        if($project->rate_list)
        {
            foreach($project->rate_list as $rate)
            {
                unset($rate->days);
                $rate->min_invest_des = $controller->showWan($rate->min_invest);
                $rate->max_invest_des = $controller->showWan($rate->max_invest);
            }
        }
        $project->typeDesc = Project::getTypeDesc($project->typeCode);
        $project->projectInterestList = $project->rate_list;
        unset($project->rate_list,$project->projectDescription,$project->projectDuration);
        $data                        = array('success'=>1,'msg'=>'ok');
        $data['result']              = $project;
        $data['regBonusTip']         = '新人赠送'.Yii::app()->params['register_reward_bonus']['number'].'元投资红包';
        $total                       = $pdata[1];
        $data['investedTotal']       = number_format($total,0);
        $data['investedTotalOrigin'] = intval($total);
        $spentTime = number_format((microtime(true) - YII_BEGIN_TIME)*1000,2);
        Yii::log('to join other segment  spent '.$spentTime.' ms','info','api.performance.info');
        $data['totalRegisters']      = $controller->formatNumber(Yii::app()->cache_php->get('TotalRegisterUser')/10000,1,true).'万';
        $spentTime = number_format((microtime(true) - YII_BEGIN_TIME)*1000,2);
        Yii::log('to redis 4.192 get TotalRegisterUser spent '.$spentTime.' ms','info','api.performance.info');
        return $data;
    }
    /**
     * 理财产品列表
     */
    public function getProjectList()
    {
        $cache = Yii::app()->cache_new->hget('projectList','phoneIndexList');
        if($cache)
            $list = json_decode($cache);
        else
        {
            $remote = HttpLib::post(Yii::app()->controller->javaApi['mobile_project_list'],array());
            if($remote->success && $remote->result->projectList)
            {
                $list  = $remote->result;
            }
            else
            {
                $this->setResult(array(
                    'success' => 0,
                    'msg'     => $remote->errorMsg,
                ));
            }
        }
        $data  = array();
        $data['msg']                 = 'ok';
        $data['success']             = 1;
        $data['showNew']             = 1;//是否显示新手
        $data['showE']               = 1;//是否显示E钱包
        $data['forNewCustomer']      = array();//新手专享
        $data['toBeOnSale']          = array();//倒计时 
        $finishedInfo = MRedis::getRepaymentInfo();
        //已还款项目
        $data['finished'] = array(
            'projectNumber'  => intval($finishedInfo['count']),
            'finishedAmount' => Helper::formatNumber($finishedInfo['amount']/100000000,1,true),
            'list'           => array(),
         );
        //已售罄项目
        $data['soldout']  = array(
            'projectNumber' => intval($finishedInfo['count2']),
            'list'          => array(),
        );
        //e钱包
        $data['ewallet']  = array(
            'min'  => Yii::app()->params['ewalletMinAmount'],
            'rate' => Yii::app()->params['ewalletRate'],
            'tip'  => '会生钱的钱包',
        );
        $data['onsale']   = array();
        $pids = array();
        $pip  = Yii::app()->cache_ext->pipeline();
        foreach($list->projectList as $v)
        {
            $pip->get($v->projectId.'.Investable');
        }
        $balances = $pip->exec();
        foreach($list->projectList as $k=>$v)
        {
            $v->projectName    = $v->subTitle;
            $v->projectBalance = $balances[$k];
            $v->procress       = Yii::app()->controller->converPoint($v->projectBalance, $v->totalAmount);
            $v->min_rate       = number_format($v->min_rate,2,'.','');
            $v->max_rate       = number_format($v->max_rate,2,'.','');
            if ($v->endTime && strtotime($v->endTime) > time())
            {
                $v->reduceDay = round((strtotime($v->endTime) - strtotime(date('Y-m-d'))) / 3600 / 24) - $v->interestFrom + 1; //预期收益天数
                $v->reduceDay = $v->reduceDay>0?$v->reduceDay:0;
            }
            unset($v->totalAmount,$v->interestFrom,$v->endTime,$v->saleEndTime);//去除不需要的字段
            if($k==0)
            {
                unset($v->onlineTime);
                $data['forNewCustomer'] = $v;
            }
            else
            {
                switch($v->statusCode)
                {
                    case 4:
                        unset($v->onlineTime);//去除不需要的字段
                        $data['onsale'][] = $v;
                        break;
                    case 9:
                        unset($v->onlineTime);
                        $data['finished']['list'][] = $v;
                        break;
                    case 8:
                        unset($v->onlineTime);
                        $data['soldout']['list'][] = $v;
                        break;
                    case 3:
                        if(MOBILEOS === 'ios')
                            $v->secondsToOnLine = strtotime($v->onlineTime) - time() + 60;
                        
                        $v->timeOnLine      = date('H:i:s',strtotime($v->onlineTime));
                        unset($v->onlineTime);
                        $data['toBeOnSale'][] = $v;
                        break;
                }
            }
        }
        $transStatus = Project::model()->isTransOnSale();
        $data['transStatus'] = $transStatus?1:0;//转让区是否有在售项目
        return $data;
    }
    /**
     * 获取项目的投资次数相关信息
     */
    public  function getInvestedNum($project_id,$typeCode,$category1)
    {
        self::model()->tranlistIni($project_id);
        $num = (int)Yii::app()->cache_new->llen('projectTransList.'.$project_id);
        $gylAndJbpIds = Yii::app()->cache_php->get('appGYLandJBPtypeids');
        $gylAndJbpIds = json_decode($gylAndJbpIds);
        $gylIds = explode(',', $gylAndJbpIds->gylIds);//供应链
        $jbpIds = explode(',', $gylAndJbpIds->jbpIds);//聚宝盆
        if($category1 ==1 && in_array($typeCode,$gylIds))
        {
            $nums = $this->getSeriesInvestedNum($gylIds);
        }
        elseif($category1==3 && in_array($typeCode, $jbpIds))//聚宝盆
        {
            $nums = $this->getSeriesInvestedNum($jbpIds);
        }
        else
        {
            $nums = $this->getSeriesInvestedNum($typeCode);
        }
        $nums['num'] = $num;//该项目购买人次
        return $nums;
    }
    /**
     * 系列理财次数
     */
    private function getSeriesInvestedNum($typeCode)
    {
        $nums = array(
            'finishedCount' => 0,
            'investAmount'  => 0,
            'investCount'   => 0,
            'projectCount'  => 0,
            'redeemCount'   => 0,
        );
        if(!$this->initSeriesNumber())
            return $nums;
        if(is_array($typeCode))//多个
        {
            $pipeline = Yii::app()->cache_new->pipeline();
            foreach($typeCode as $code)
            {
                $pipeline->hget('projectTypeSummary',$code);
            }
            $dataList = $pipeline->exec();
            foreach($dataList as $data)
            {
                $data = json_decode($data);
                $nums['finishedCount'] += $data->finishedCount;
                $nums['investAmount']  += $data->investAmount;
                $nums['investCount']   += $data->investCount;
                $nums['projectCount']  += $data->projectCount;
                $nums['redeemCount']   += $data->redeemCount;
            }
            return $nums;
        }
        else
        {
            //单个typeCode
            $cache = Yii::app()->cache_new->hget('projectTypeSummary',$typeCode);
            if(!$cache)
                return $nums;
            $cache = json_decode($cache);
            return array(
                'finishedCount' => (int)$cache->finishedCount,//已还款数量
                'investAmount'  => (int)$cache->investAmount,//该系列投资金额
                'investCount'   => (int)$cache->investCount,//该系列投资笔数
                'projectCount'  => (int)$cache->projectCount,//项目数量
                'redeemCount'   => (int)$cache->redeemCount,//提前还款项目数量
            );
        }
    }
    /**
     * 初始化系列理财次数
     */
    private function initSeriesNumber()
    {
        $cache = Yii::app()->cache_new;
        if(!$cache->exists('projectTypeSummary'))
        {
            $remote = HttpLib::get('project/type/summary.json',array());
            if(!$remote->success)
                return false;
        }
        return true;
    }
    /**
     * 转让项目
     */
    public function getTransByPK($id)
    {
        $cache  = Yii::app()->cache_new->hget('transferProjectDetail',$id);
        if($cache)
            $project = json_decode($cache);
        else
        {
            $remote = HttpLib::get($this->javaApi['transfer_detail'],array('id'=>$id));
            if($remote->success)
            {
                $project = $remote->result;
            }
            else
            {
                $this->setResult(array(
                    'success' => 0,
                    'msg'     => $remote->errorMsg,
                ));
            }
        }
        $project->projectBalance  = self::model()->getBalance($id);
        $project->reduceDay       = round((strtotime($project->saleEndTime) - strtotime(date('Y-m-d'))) / 3600 / 24) - $project->interestFrom + 1; //预期收益天数
        $project->projectInterest = number_format($project->projectInterest*100,2,'.','');
        return $project;
    }
    /**
     * 初始化项目的购买列表
     */
    public function tranlistIni($projectId)
    {
        if(!Yii::app()->cache_new->hget('projectTransListTag',$projectId))
        {
            $remote = HttpLib::get('transaction/init/project/transactions.json', array('project_id'=>$projectId));
            if(!$remote->success)
            {
                $this->setResult(array(
                    'success' => 0,
                    'msg'     => $remote->errorMsg,
                ));
            }
        }
    }
    /**
     * 转让区是否有在售项目
     * @return boolean [description]
     */
    public function isTransOnSale()
    {
        $cache = Yii::app()->cache2;
        if($cache->get('SellingTransferProjectCount') === null)
        {
            $remote = HttpLib::post('transfer/selling/transfer/project/init.json',array());
            if(!$remote->success)
                return false;
        }
        if($cache->get('SellingTransferProjectCount')>0)
            return true;
        return false;
    }
}
